import React, { useState, useEffect, useRef } from 'react';
import { 
  Modal, 
  Button, 
  Space, 
  Typography, 
  Select, 
  Tooltip,
  Card,
  Row,
  Col,
  message,
  FloatButton,
  Tabs,
  Slider,
  Statistic
} from 'antd';
import {
  NodeIndexOutlined,
  ApartmentOutlined,
  SaveOutlined,
  UndoOutlined,
  RedoOutlined,
  ZoomInOutlined,
  ZoomOutOutlined,
  ReloadOutlined,
  ToolOutlined,
  PlusOutlined,
  EditOutlined,
  PlayCircleOutlined,
  PauseCircleOutlined,
  FullscreenOutlined,
  InfoCircleOutlined,
  SettingOutlined,
  BranchesOutlined,
  ClusterOutlined,
  SisternodeOutlined,
  AppstoreOutlined,
  ThunderboltOutlined
} from '@ant-design/icons';

import GraphVisualizationHub from '../../../../components/GraphVisualizationHub';
import NodeEditor from '../../../../components/NodeEditor';
import RelationEditor from '../../../../components/RelationEditor';
import { getGraphTypeStyle, getLayoutStyle } from '../../../../styles/graphThemes';

const { Text, Title } = Typography;
const { Option } = Select;

const GraphEditModal = ({
  visible, 
  onCancel, 
  graphData, 
  onSave,
  graphTypeDefinitions,
  graphLayoutDefinitions 
}) => {
  const [graphType, setGraphType] = useState('knowledge');
  const [graphStyle, setGraphStyle] = useState('force');
  const [graphNodes, setGraphNodes] = useState([]);
  const [graphEdges, setGraphEdges] = useState([]);
  const [nodeEditorVisible, setNodeEditorVisible] = useState(false);
  const [relationEditorVisible, setRelationEditorVisible] = useState(false);
  const [editingNode, setEditingNode] = useState(null);
  const [editingRelation, setEditingRelation] = useState(null);
  const [hasChanges, setHasChanges] = useState(false);
  const [zoomLevel, setZoomLevel] = useState(1);
  const [isSimulationRunning, setIsSimulationRunning] = useState(true);
  const [animationSpeed, setAnimationSpeed] = useState(0.3);
  const [layoutConfig, setLayoutConfig] = useState({});
  const [isFullscreen, setIsFullscreen] = useState(false);
  
  // 使用ref引用GraphVisualizationHub组件
  const visualizationRef = useRef(null);

  // 布局定义
  const layoutDefinitions = {
    force: { 
      name: '力导向布局', 
      description: '基于物理模拟的节点自然分布',
      icon: <ThunderboltOutlined />
    },
    circular: { 
      name: '环形布局', 
      description: '节点均匀分布在圆周上',
      icon: <div style={{ width: 14, height: 14, border: '2px solid currentColor', borderRadius: '50%' }} />
    },
    hierarchical: { 
      name: '层次布局', 
      description: '按层级关系从上到下排列',
      icon: <ApartmentOutlined />
    },
    grid: { 
      name: '网格布局', 
      description: '节点均匀分布在网格中',
      icon: <AppstoreOutlined />
    },
    radial: { 
      name: '辐射布局', 
      description: '从中心向外辐射的树状结构',
      icon: <SisternodeOutlined />
    },
    tree: { 
      name: '树形布局', 
      description: '自上而下或自左向右的树状结构',
      icon: <BranchesOutlined />
    }
  };

  useEffect(() => {
    if (graphData) {
      try {
        // 使用深拷贝来避免直接修改原始数据
        setGraphNodes(JSON.parse(JSON.stringify(graphData.nodes || [])));
        setGraphEdges(JSON.parse(JSON.stringify(graphData.edges || [])));
        setGraphType(graphData.type || 'knowledge');
        setGraphStyle(graphData.layout || 'force');
        setHasChanges(false);
      } catch (error) {
        console.error("处理图谱数据时出错:", error);
        // 设置默认空数组，避免渲染错误
        setGraphNodes([]);
        setGraphEdges([]);
      }
    } else {
      // 如果没有图谱数据，设置为空数组
      setGraphNodes([]);
      setGraphEdges([]);
    }
  }, [graphData]);

  // 根据布局样式动态生成配置
  useEffect(() => {
    console.log('🔄 布局样式变化，当前样式:', graphStyle);
    
    let config = {};
    // 为不同的布局样式提供独特的视觉效果和参数
    switch (graphStyle) {
      case 'force':
        config = {
          name: 'force',
          description: '经典力导向布局，模拟节点间的斥力和引力。',
          simulation: {
            gravity: -400,
            linkDistance: 120,
            chargeStrength: -600,
          },
          visuals: {
            linkCurvature: 0.1,
            showArrows: true,
          }
        };
        break;
      case 'hierarchical':
        config = {
          name: 'hierarchical',
          description: '层次结构布局，清晰展示层级关系。',
          treeLayout: {
            direction: 'TB', // Top-to-Bottom
            nodeSpacing: 150,
            levelSpacing: 180,
          },
          visuals: {
            linkCurvature: 0.5,
            showArrows: true,
          }
        };
        break;
      case 'circular':
        config = {
          name: 'circular',
          description: '环形布局，适合展示网络中的对等关系。',
          circularLayout: {
            radius: 350,
          },
          visuals: {
            linkCurvature: 0,
            showArrows: false,
          }
        };
        break;
      case 'grid':
        config = {
            name: 'grid',
            description: '网格布局，将节点整齐排列。',
            gridLayout: {
                rows: Math.ceil(Math.sqrt(graphNodes.length)),
                cols: Math.ceil(Math.sqrt(graphNodes.length)),
                nodeSpacing: 200,
            },
            visuals: {
                linkCurvature: 0,
                showArrows: true,
            }
        };
        break;
      case 'radial':
        config = {
            name: 'radial',
            description: '辐射布局，从中心节点向外辐射。',
            radialLayout: {
                radius: 400,
                focusNode: graphNodes.length > 0 ? graphNodes[0].id : null,
            },
            visuals: {
                linkCurvature: 0.2,
                showArrows: true,
            }
        };
        break;
      case 'tree':
        config = {
            name: 'tree',
            description: '树形布局，自左向右展示层级结构。',
            treeLayout: {
                direction: 'LR', // Left-to-Right
                nodeSpacing: 120,
                levelSpacing: 150,
            },
            visuals: {
                linkCurvature: 0.3,
                showArrows: true,
            }
        };
        break;
      default:
        config = { name: 'force', description: '默认布局' };
    }
    
    // 保留之前的自定义参数设置
    if (layoutConfig && layoutConfig.name === config.name) {
      // 合并之前的参数设置
      config = {
        ...config,
        simulation: {
          ...config.simulation,
          ...(layoutConfig.simulation || {})
        },
        circularLayout: {
          ...config.circularLayout,
          ...(layoutConfig.circularLayout || {})
        },
        treeLayout: {
          ...config.treeLayout,
          ...(layoutConfig.treeLayout || {})
        },
        radialLayout: {
          ...config.radialLayout,
          ...(layoutConfig.radialLayout || {})
        },
        gridLayout: {
          ...config.gridLayout,
          ...(layoutConfig.gridLayout || {})
        }
      };
    }
    
    console.log('📋 生成的布局配置:', config);
    setLayoutConfig(config);
    
    // 切换布局视为一项更改
    if (graphData) { // 仅在已有数据时标记为更改
        setHasChanges(true);
    }
    
    // 强制触发GraphVisualizationHub重新渲染
    if (visualizationRef.current && visualizationRef.current.updateLayout) {
      console.log('🔧 调用updateLayout方法');
      visualizationRef.current.updateLayout(graphStyle, config);
    }
    
  }, [graphStyle, graphData, graphNodes]); // 依赖graphNodes以在节点数变化时重新计算grid/radial

  // 获取当前图谱类型的节点类型列表
  const getNodeTypeOptions = () => {
    if (graphTypeDefinitions && graphTypeDefinitions[graphType]) {
      return graphTypeDefinitions[graphType].nodeTypes?.map(type => ({
        label: type,
        value: type.toLowerCase().replace(/\s+/g, '_')
      })) || [];
    }
    return [];
  };
  
  // 获取当前图谱类型的关系类型列表
  const getRelationTypeOptions = () => {
    if (graphTypeDefinitions && graphTypeDefinitions[graphType]) {
      return graphTypeDefinitions[graphType].relationTypes?.map(type => ({
        label: type,
        value: type.toLowerCase().replace(/\s+/g, '_')
      })) || [];
    }
    return [];
  };

  // 处理节点点击 - 编辑模式可以编辑节点
  const handleNodeClick = (node) => {
    setEditingNode(node);
    setNodeEditorVisible(true);
  };

  // 处理关系点击 - 编辑模式可以编辑关系
  const handleEdgeClick = (edge) => {
    setEditingRelation(edge);
    setRelationEditorVisible(true);
  };

  // 添加节点
  const handleAddNode = () => {
    setEditingNode(null);
    setNodeEditorVisible(true);
  };

  // 添加关系
  const handleAddRelation = () => {
    if (graphNodes.length < 2) {
      message.warning('至少需要两个节点才能创建关系');
      return;
    }
    setEditingRelation(null);
    setRelationEditorVisible(true);
  };

  // 保存节点
  const handleSaveNode = (nodeData) => {
    if (editingNode) {
      // 编辑节点
      setGraphNodes(prev => prev.map(node => 
        node.id === editingNode.id ? nodeData : node
      ));
    } else {
      // 添加节点
      const newNode = {
        ...nodeData,
        id: `node_${Date.now()}`,
        x: Math.random() * 400 + 100,
        y: Math.random() * 300 + 100
      };
      setGraphNodes(prev => [...prev, newNode]);
    }
    setNodeEditorVisible(false);
    setHasChanges(true);
  };

  // 保存关系
  const handleSaveRelation = (relationData) => {
    if (editingRelation) {
      // 编辑关系
      setGraphEdges(prev => prev.map(edge => 
        edge.id === editingRelation.id ? relationData : edge
      ));
    } else {
      // 添加关系
      const newRelation = {
        ...relationData,
        id: `edge_${Date.now()}`
      };
      setGraphEdges(prev => [...prev, newRelation]);
    }
    setRelationEditorVisible(false);
    setHasChanges(true);
  };

  // 更新节点位置
  const handleNodePositionUpdate = (nodeId, x, y) => {
    setGraphNodes(prev => prev.map(node => 
      node.id === nodeId ? { ...node, x, y } : node
    ));
    setHasChanges(true);
  };

  // 保存图谱
  const handleSave = () => {
    try {
      // 验证节点和边的有效性
      const validNodes = graphNodes.filter(node => node && node.id);
      const validEdges = graphEdges.filter(edge => {
        // 确保边的源节点和目标节点都存在
        return edge && edge.id && edge.source && edge.target && 
               validNodes.some(node => node.id === edge.source) && 
               validNodes.some(node => node.id === edge.target);
      });
      
      const updatedGraphData = {
        ...graphData,
        nodes: validNodes,
        edges: validEdges,
        type: graphType,
        layout: graphStyle,
        entities: validNodes.length,
        relations: validEdges.length
      };
      
      onSave(updatedGraphData);
      setHasChanges(false);
      message.success('图谱保存成功');
    } catch (error) {
      console.error("保存图谱时出错:", error);
      message.error('保存图谱失败，请检查数据格式');
    }
  };

  // 取消编辑
  const handleCancel = () => {
    if (hasChanges) {
      Modal.confirm({
        title: '确认取消',
        content: '您有未保存的更改，确定要取消吗？',
        onOk: () => {
          onCancel();
        }
      });
    } else {
      onCancel();
    }
  };

  // 全屏切换
  const toggleFullscreen = () => {
    setIsFullscreen(!isFullscreen);
  };

  // 获取当前图谱类型的样式
  const getCurrentGraphTypeStyle = () => {
    return getGraphTypeStyle(graphType);
  };

  // 获取当前布局类型的样式
  const getCurrentLayoutStyle = () => {
    return getLayoutStyle(graphStyle);
  };

  // 根据图谱类型推荐最适合的布局样式
  const getRecommendedLayout = (type) => {
    const recommendations = {
      knowledge: 'force',        // 知识图谱 -> 力导向布局
      concept: 'hierarchical',   // 概念图谱 -> 层次布局
      mind: 'tree',             // 思维导图 -> 树形布局
      topic: 'circular',        // 主题图谱 -> 环形布局
      semantic: 'force',        // 语义网络 -> 力导向布局
      ontology: 'hierarchical', // 本体图谱 -> 层次布局
      social: 'force',          // 社交网络 -> 力导向布局
      causal: 'hierarchical',   // 因果图谱 -> 层次布局
      flow: 'tree',             // 流程图谱 -> 树形布局
      network: 'force',         // 网络图谱 -> 力导向布局
      innovation: 'radial',     // 创新图谱 -> 辐射布局
      research: 'hierarchical', // 研究图谱 -> 层次布局
      education: 'tree'         // 教育图谱 -> 树形布局
    };
    return recommendations[type] || 'force';
  };

  // 获取推荐布局的名称
  const getRecommendedLayoutName = (type) => {
    const recommendedLayout = getRecommendedLayout(type);
    return layoutDefinitions[recommendedLayout]?.name || '力导向布局';
  };

  // 根据布局获取匹配的图谱类型
  const getMatchingGraphType = (layoutStyle) => {
    // 布局与图谱类型的映射关系
    const layoutToTypeMap = {
      force: 'knowledge',
      hierarchical: 'concept',
      tree: 'mind',
      circular: 'topic',
      radial: 'innovation',
      grid: 'network'
    };
    
    return layoutToTypeMap[layoutStyle] || 'knowledge';
  };
  
  // 获取当前布局的描述
  const getCurrentLayoutDescription = () => {
    const layoutNames = {
      force: '力导向布局',
      hierarchical: '层次布局',
      tree: '树形布局',
      circular: '环形布局',
      radial: '辐射布局',
      grid: '网格布局'
    };
    
    return layoutNames[graphStyle] || graphStyle;
  };

  // 获取快速布局模板配置
  const getQuickTemplates = () => {
    return [
      {
        name: '知识网络布局',
        type: 'knowledge',
        layout: 'force',
        icon: <NodeIndexOutlined />
      },
      {
        name: '概念层次布局',
        type: 'concept',
        layout: 'hierarchical',
        icon: <ApartmentOutlined />
      },
      {
        name: '思维导图布局',
        type: 'mind',
        layout: 'tree',
        icon: <BranchesOutlined />
      },
      {
        name: '主题环形布局',
        type: 'topic',
        layout: 'circular',
        icon: <ClusterOutlined />
      },
      {
        name: '创新辐射布局',
        type: 'innovation',
        layout: 'radial',
        icon: <SisternodeOutlined />
      }
    ];
  };

  return (
    <>
      <Modal
        title="编辑图谱"
        open={visible}
        onCancel={handleCancel}
        width={1400}
        centered={true}
        styles={{ body: { padding: '12px' } }}
        footer={[
          <Button key="cancel" onClick={handleCancel}>
            取消
          </Button>,
          <Button 
            key="save" 
            type="primary" 
            icon={<SaveOutlined />} 
            onClick={handleSave} 
            disabled={!hasChanges}
            style={{ 
              background: hasChanges ? getCurrentGraphTypeStyle().nodeColor({}) : undefined,
              borderColor: hasChanges ? getCurrentGraphTypeStyle().nodeColor({}) : undefined
            }}
          >
            保存更改
          </Button>
        ]}
      >
        {graphData && (
          <div>
            {/* 编辑状态信息 - 压缩版 */}
            <Card size="small" style={{ marginBottom: '8px' }}>
              <Row gutter={16} align="middle">
                <Col flex="auto">
                  <Space size="large" align="center">
                    <div>
                      <Title level={5} style={{ margin: 0 }}>
                        {graphData.name}
                      </Title>
                    </div>
                    <div style={{ textAlign: 'center' }}>
                      <Text style={{ 
                        fontSize: '16px', 
                        fontWeight: 'bold', 
                        color: getCurrentGraphTypeStyle().nodeColor({}) 
                      }}>
                        {graphNodes.length}
                      </Text>
                      <Text type="secondary" style={{ fontSize: '12px', marginLeft: '4px' }}>实体</Text>
                    </div>
                    <div style={{ textAlign: 'center' }}>
                      <Text style={{ 
                        fontSize: '16px', 
                        fontWeight: 'bold', 
                        color: getCurrentGraphTypeStyle().edgeColor({})
                      }}>
                        {graphEdges.length}
                      </Text>
                      <Text type="secondary" style={{ fontSize: '12px', marginLeft: '4px' }}>关系</Text>
                    </div>
                    {hasChanges && (
                      <div style={{ textAlign: 'center' }}>
                        <Text style={{ fontSize: '14px', fontWeight: 'bold', color: '#fa8c16' }}>
                          未保存
                        </Text>
                      </div>
                    )}
                  </Space>
                </Col>
                <Col>
                  <Space>
                    <Button 
                      size="small" 
                      icon={<NodeIndexOutlined />} 
                      onClick={handleAddNode}
                      type="primary"
                      style={{ 
                        background: getCurrentGraphTypeStyle().nodeColor({}),
                        borderColor: getCurrentGraphTypeStyle().nodeColor({})
                      }}
                    >
                      添加实体
                    </Button>
                    <Button 
                      size="small" 
                      icon={<ApartmentOutlined />} 
                      onClick={handleAddRelation}
                      type="primary"
                      style={{ 
                        background: getCurrentGraphTypeStyle().edgeColor({}),
                        borderColor: getCurrentGraphTypeStyle().edgeColor({})
                      }}
                    >
                      添加关系
                    </Button>
                  </Space>
                </Col>
              </Row>
            </Card>
            
            {/* 布局选择控制面板 */}
            <Card size="small" style={{ marginBottom: '8px' }}>
              <Row gutter={16} align="middle">
                <Col span={24}>
                  <div style={{ marginBottom: '8px' }}>
                    <Text strong style={{ fontSize: '13px' }}>图谱布局样式</Text>
                    <Text type="secondary" style={{ fontSize: '11px', marginLeft: '8px' }}>
                      选择不同的布局算法来展示图谱
                    </Text>
                  </div>
                  
                  {/* 布局选择按钮组 */}
                  <Space wrap>
                    {Object.entries(layoutDefinitions).map(([layoutKey, layout]) => (
                      <Button
                        key={layoutKey}
                        type={graphStyle === layoutKey ? 'primary' : 'default'}
                        size="small"
                        onClick={() => {
                          console.log('🎯 点击切换布局:', layoutKey, '当前布局:', graphStyle);
                          console.log('🎯 点击事件触发，准备切换布局');
                          setGraphStyle(layoutKey);
                          console.log('🎯 setGraphStyle 调用完成');
                          message.success(`已切换到${layout.name}`);
                        }}
                        style={{ 
                          display: 'flex',
                          alignItems: 'center',
                          gap: '4px'
                        }}
                      >
                        {layout.icon}
                        <span>{layout.name}</span>
                      </Button>
                    ))}
                  </Space>
                  
                  {/* 当前布局描述 */}
                  <div style={{ marginTop: '8px', padding: '8px', background: '#f5f5f5', borderRadius: '4px' }}>
                    <Text type="secondary" style={{ fontSize: '12px' }}>
                      {layoutDefinitions[graphStyle]?.description}
                    </Text>
                  </div>
                </Col>
              </Row>
            </Card>
            
            {/* 图谱编辑区域 */}
            <div style={{ 
              border: '1px solid #d9d9d9', 
              borderRadius: '6px',
              background: getCurrentGraphTypeStyle().background || '#fff',
              position: isFullscreen ? 'fixed' : 'relative',
              top: isFullscreen ? 0 : 'auto',
              left: isFullscreen ? 0 : 'auto',
              width: isFullscreen ? '100vw' : 'auto',
              height: isFullscreen ? '100vh' : 'auto',
              zIndex: isFullscreen ? 9999 : 'auto',
              overflow: 'hidden'
            }}>
              {/* 当前布局信息显示 */}
              <div style={{ 
                position: 'absolute', 
                top: 10, 
                right: 10, 
                zIndex: 10, 
                background: 'rgba(255,255,255,0.9)', 
                padding: '6px 12px', 
                borderRadius: '6px',
                fontSize: '12px',
                display: 'flex',
                alignItems: 'center',
                gap: '8px',
                boxShadow: '0 2px 8px rgba(0,0,0,0.1)'
              }}>
                {layoutDefinitions[graphStyle]?.icon}
                <Text strong style={{ fontSize: '12px' }}>
                  {layoutDefinitions[graphStyle]?.name}
                </Text>
              </div>
              
              <GraphVisualizationHub
                ref={visualizationRef}
                nodes={graphNodes || []}
                edges={graphEdges || []}
                graphType={graphType}
                layout={graphStyle}
                layoutConfig={layoutConfig}
                onLayoutChange={(newLayout) => {
                  console.log('📡 接收到布局变化回调:', newLayout);
                  setGraphStyle(newLayout);
                }}
                onNodeClick={handleNodeClick}
                onEdgeClick={handleEdgeClick}
                onNodePositionUpdate={handleNodePositionUpdate}
                editable={true}
                height={isFullscreen ? window.innerHeight : 400}
                zoom={zoomLevel}
                animationSpeed={animationSpeed}
                isSimulationRunning={isSimulationRunning}
                isFullscreen={isFullscreen}
                onToggleFullscreen={toggleFullscreen}
                key={`graph-${graphStyle}-${Date.now()}-${graphNodes.length}-${graphEdges.length}`}
                errorHandler={(error) => {
                  console.error("图谱渲染错误:", error);
                  message.error('图谱渲染出现问题，请检查数据格式');
                }}
              />
            </div>
          </div>
        )}
      </Modal>

      {/* 节点编辑器 */}
      <NodeEditor
        visible={nodeEditorVisible}
        onCancel={() => setNodeEditorVisible(false)}
        onSave={handleSaveNode}
        nodeData={editingNode}
        mode={editingNode ? 'edit' : 'add'}
        nodeTypeOptions={getNodeTypeOptions()}
        graphType={graphType}
      />

      {/* 关系编辑器 */}
      <RelationEditor
        visible={relationEditorVisible}
        onCancel={() => setRelationEditorVisible(false)}
        onSave={handleSaveRelation}
        relationData={editingRelation}
        nodes={graphNodes}
        mode={editingRelation ? 'edit' : 'add'}
        relationTypeOptions={getRelationTypeOptions()}
        graphType={graphType}
      />

      {/* 编辑模式浮动按钮 */}
      {visible && (
        <FloatButton.Group
          trigger="hover"
          type="primary"
          style={{ right: 24, bottom: 24 }}
          icon={<ToolOutlined />}
        >
          <FloatButton 
            icon={<NodeIndexOutlined />} 
            tooltip="添加节点"
            onClick={handleAddNode}
          />
          <FloatButton 
            icon={<ApartmentOutlined />} 
            tooltip="添加关系"
            onClick={handleAddRelation}
          />
          <FloatButton 
            icon={<SaveOutlined />} 
            tooltip="保存更改"
            onClick={handleSave}
            type={hasChanges ? 'primary' : 'default'}
          />
        </FloatButton.Group>
      )}
    </>
  );
};

export default GraphEditModal;
